package com.github.common.util.lang;

import lombok.SneakyThrows;
import com.github.common.util.collection.MapUtil;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * TODO： 处理数据库字段名带下划线至java驼峰field名
 */
public class MapToObjUtil {

    /**
     * 把source转为target
     *
     * @param source source
     * @param target target
     * @param <T>    返回值类型
     * @return 返回值
     * @throws Exception newInstance可能会抛出的异常
     */
    @SneakyThrows
    public static <T> T mapToObj(Map source, Class<T> target) {
        Field[] fields = target.getDeclaredFields();
        T o = target.newInstance();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getType() == Integer.class) {
                field.set(o, MapUtil.getInt(source, field.getName()));
            } else if (field.getType() == int.class) {
                field.set(o, MapUtil.getInt(source, field.getName()));
            } else if (field.getType() == Long.class) {
                field.set(o, MapUtil.getLong(source, field.getName()));
            } else if (field.getType() == String.class) {
                field.set(o, MapUtil.getStr(source, field.getName()));
            } else if (field.getType() == Boolean.class) {
                field.set(o, MapUtil.getBoolean(source, field.getName()));
            } else if (field.getType() == Byte.class) {
                field.set(o, MapUtil.getByte(source, field.getName()));
            } else {
                throw new UnsupportedOperationException(field.getType().getName());
            }
        }
        return o;
    }

    public static <T> List<T> mapToObjs(List<Map<String, Object>> sources, Class<T> target) {
        AssertUtil.notEmpty(sources, "sources");
        return sources.stream().map(source -> mapToObj(source, target)).collect(Collectors.toList());
    }
}